package com.oliver.picturebackend.manager.template;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.oliver.picturebackend.config.CosClientConfig;
import com.oliver.picturebackend.exception.BusinessException;
import com.oliver.picturebackend.exception.ErrorCode;
import com.oliver.picturebackend.manager.CosManager;
import com.oliver.picturebackend.model.dto.file.UploadPictureResult;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.model.ciModel.persistence.ImageInfo;
import lombok.extern.slf4j.Slf4j;

import javax.annotation.Resource;
import java.io.File;
import java.util.Date;

/**
 * @ClassName PictureUploadTemplate
 * @Description 图片上传模板类
 * @Author snow
 * @Date 2024/12/15 15:08
 **/

@Slf4j
public abstract class PictureUploadTemplate {

    @Resource
    private CosManager cosManager;

    @Resource
    private CosClientConfig cosClientConfig;

    public UploadPictureResult uploadPicture(Object inputSource, String uploadPathPrefix){
        //  todo 校验图片
        validPicture(inputSource);
        //  图片上传路径
        String uuid = RandomUtil.randomString(16);
        String originFileName= getOriginFileName(inputSource);
        //  日期_前缀.后缀
        String suffix = FileUtil.getSuffix(originFileName);
        //  默认的后缀名jpg
        if (StrUtil.isBlank(suffix)){
            suffix = "jpg";
        }
        String uploadFileName = String.format("%s_%s.%s", DateUtil.formatDate(new Date()),uuid, suffix);
        String uploadFile = String.format("%s/%s",uploadPathPrefix,uploadFileName);
        File file = null;
        try{
            //  创建临时文件
            file = File.createTempFile(uploadFile,null);
            //  处理图片
            processFile(inputSource, file);
            //  图片上传
            PutObjectResult putObjectResult = cosManager.putObject(uploadFile, file);
            //  获取到图片信息
            ImageInfo imageInfo = putObjectResult.getCiUploadResult().getOriginalInfo().getImageInfo();
            //  封装返回类
            return getUploadPictureResult(imageInfo, uploadFile, originFileName, file);
        }catch (Exception e){
            log.error("图片上传失败",e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"上传文件失败");
        }finally {
            //  删除临时文件
            this.deleteTemplate(file);
        }
    }
    protected abstract void validPicture(Object inputSource);

    protected abstract String getOriginFileName(Object inputSource);

    protected abstract void processFile(Object inputSource, File file) throws Exception;


    /**
     * 删除临时文件
     * @param file
     */
    private void deleteTemplate(File file) {
        if (file == null){
            return;
        }
        //  删除临时文件
        boolean delete = file.delete();
        if (!delete){
            log.error("file upload error, filePath = {}",file.getAbsolutePath());
        }
    }

    /**
     * 封装返回类
     * @param imageInfo
     * @param uploadFile
     * @param originFileName
     * @param file
     * @return
     */
    private UploadPictureResult getUploadPictureResult(ImageInfo imageInfo, String uploadFile, String originFileName, File file) {
        UploadPictureResult uploadPictureResult = new UploadPictureResult();
        int width = imageInfo.getWidth();
        int height = imageInfo.getHeight();
        double picScale = NumberUtil.round((width * 1.0 / height),2).doubleValue();
        uploadPictureResult.setUrl(cosClientConfig.getHost() + "/" + uploadFile);
        uploadPictureResult.setPicName(FileUtil.mainName(originFileName));
        uploadPictureResult.setPicSize(FileUtil.size(file));
        uploadPictureResult.setPicWidth(width);
        uploadPictureResult.setPicHeight(height);
        uploadPictureResult.setPicScale(picScale);
        uploadPictureResult.setPicFormat(imageInfo.getFormat());
        return uploadPictureResult;
    }


}
